package com.coins.common.utils;

import java.util.AbstractMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;

/**
 * 功能：去重复消息队列
 *
 * @author 任梁荣
 * */
public class AntiDuplicateLinkedBlockingQueue<Key, Value> {

	private final LinkedList<Entry<Key, Value>> list = new LinkedList<Entry<Key, Value>>();

	private final HashSet<Key> keySet = new HashSet<Key>();

	public synchronized int size() {
		return list.size();
	}

	public synchronized boolean put(Key key, Value value) {
		if (keySet.contains(key)) {
			return false;
		}
		list.add(new AbstractMap.SimpleEntry<Key, Value>(key, value));
		keySet.add(key);
		notifyAll();
		return true;
	}

	public synchronized Entry<Key, Value> take() throws InterruptedException {
		while (list.size() == 0) {
			wait();
		}
		Entry<Key, Value> entry = list.removeFirst();
		keySet.remove(entry.getKey());
		return entry;
	}

	public synchronized void clear() {
		list.clear();
		keySet.clear();
	}

}
